import { defineStore } from 'pinia'
import { store } from '../index'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'
import { useStorage } from '@/hooks/web/useStorage'

const { getStorage, setStorage } = useStorage('localStorage')

const elLocaleMap = {
  'zh-CN': zhCn,
  en
}

export const useLocaleStore = defineStore('locales', {
  state: () => {
    const savedLang = getStorage('lang') ?? 'zh-CN'
    return {
      currentLocale: {
        lang: savedLang,
        elLocale: elLocaleMap[savedLang]
      },
      localeMap: [
        { lang: 'zh-CN', name: '简体中文' },
        { lang: 'en', name: 'English' }
      ]
    }
  },
  getters: {
    getCurrentLocale: (state) => state.currentLocale,
    getLocaleMap: (state) => state.localeMap,
  },
  actions: {
    setCurrentLocale(locale) {
      this.currentLocale = {
        ...locale,
        elLocale: elLocaleMap[locale.lang]
      }
      setStorage('lang', locale.lang)
    }
  }
})

export const useLocaleStoreWithOut = () => useLocaleStore(store)
